package com.dj.product.k2faas.jpa.utils;

import com.dj.product.k2faas.common.enums.DBType;
import com.dj.product.k2faas.jpa.config.ProxyDataSourceInterceptor;
import com.zaxxer.hikari.HikariDataSource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.boot.jdbc.DataSourceBuilder;

/**
 * Created by 丁建 on 2025/9/23 09:37
 *
 * @author 丁建
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DataSourceUtil {

    public static HikariDataSource getDataSource(DBType dbType, String url, String username, String password, int connectionTimeout, int maxPoolSize,
                                                 int minimumIdle, int idleTimeout, int maxLifetime, boolean autoCommit, boolean proxy) {
        var dataSource = DataSourceBuilder.create()
                                          .type(HikariDataSource.class)
                                          .driverClassName(dbType.getDriverName())
                                          .password(password)
                                          .url(url)
                                          .username(username)
                                          .build();
        dataSource.setAutoCommit(autoCommit);
        dataSource.setConnectionInitSql(dbType.getConnectionInitSql());
        dataSource.setConnectionTimeout(connectionTimeout);
        dataSource.setMaximumPoolSize(maxPoolSize);
        dataSource.setMinimumIdle(minimumIdle);
        dataSource.setIdleTimeout(idleTimeout);
        dataSource.setMaxLifetime(maxLifetime);

        if (proxy) {
            log.debug("开始建立数据库代理，以使得打印SQL日志。");
            final ProxyFactory factory = new ProxyFactory(dataSource);
            factory.setProxyTargetClass(true);
            factory.addAdvice(new ProxyDataSourceInterceptor(dataSource).setDataSourceName("数据库连接测试"));
            return (HikariDataSource) factory.getProxy();
        } else {
            log.debug("当前配置，不支持打印SQL日志。若需打印，请配置：logging.level.net.ttddyy.dsproxy.listener.logging=DEBUG");
            return dataSource;
        }
    }

    public static HikariDataSource getDataSource(DBType dbType, String url, String username, String password, boolean proxy) {
        return getDataSource(dbType, url, username, password, 60000, 10, 3, 30000, 2000000, true, true);
    }

}
